import axios from 'axios';
import {
  Message
} from 'element-ui';
import router from './../router'
/* ajax-get */
export const fetch = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: url,
      params: data,
      headers: {
        token: sessionStorage.getItem('h_token'),
      }
    }).then(resp => {
      if ((resp.data.code == 404 || resp.data.code == 401)) {
        window.location.href = "#/Login"
      }
      resolve(resp)
    }).catch(err => {
      if (err.status == 500 || err.status == 404) {
        Message({
          showClose: true,
          message: '服务器错误！'
        })
      }
      reject(err);
    })
  })
}
/* json-post */
export const postJson = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      data: data,
      headers: {
        'Content-type': 'application/json',
        token: sessionStorage.getItem('h_token')
      }
    }).then(resp => {
      if ((resp.data.code == 404 || resp.data.code == 401)) {
        window.location.href = "#/Login"
      }
      resolve(resp)
    }).catch(err => {
      if (err.status == 500 || err.status == 404) {
        Message({
          showClose: true,
          message: '服务器错误！'
        })
      }
      reject(err);
    })
  })
}
/* json-put */
export const putJson = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'put',
      url: url,
      data: data,
      headers: {
        token: sessionStorage.getItem('h_token')
      }
    }).then(resp => {
      if ((resp.data.code == 404 || resp.data.code == 401)) {
        window.location.href = "#/Login"
      }
      resolve(resp)
    }).catch(err => {
      if (err.status == 500 || err.status == 404) {
        Message({
          showClose: true,
          message: '服务器错误！'
        })
      }
      reject(err);
    })
  })
}

/* ajax-post */
export const postData = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      headers: {
        'Content-type': 'application/x-www-form-urlencoded',
        token: sessionStorage.getItem('h_token')
      },
      data: data,
      transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }],
    }).then(resp => {
      if ((resp.data.code == 404 || resp.data.code == 401)) {
        window.location.href = "#/Login"
      }
      resolve(resp)
    }).catch(err => {
      if (err.status == 500 || err.status == 404) {
        Message({
          showClose: true,
          message: '服务器错误！'
        })
      }
      reject(err);
    })
  })
}
